import { NextResponse } from 'next/server';
import type { NextApiResponse } from 'next';
import { serialize, CookieSerializeOptions } from 'cookie';

export function jsonResponse(status: number, data: any, init?: ResponseInit) {
  return new NextResponse(JSON.stringify(data), {
    ...init,
    status,
    headers: {
      ...init?.headers,
      'Content-Type': 'application/json',
    },
  });
}

export const setCookie = (res: NextApiResponse, name: string, value: unknown, options: CookieSerializeOptions = {}) => {
  const stringValue = typeof value === 'object' ? `j:${JSON.stringify(value)}` : String(value);
  const params = {
    path: '/',
    secure: false,
    ...options,
  };
  // maxAge使用秒做单位 expires使用毫秒做单位 二者同时存在maxAge生效
  if ('maxAge' in options) {
    params.expires = new Date(Date.now() + (options.maxAge as number));
    params.maxAge /= 1000;
  }

  res.setHeader('Set-Cookie', serialize(name, stringValue, params));
};
